<?php 

    //是否为登录页,防止每个页面都加载
    $is_login_page = ((param(0) == 'user') && (param(1) == 'login'));
    //是否为个人资料页
    $is_my_page = (param(0) == 'my') && (param(1) === '');
    $is_xcx_login_my_page = ($is_login_page || $is_my_page);

    //当前页面类型
    $qrcode_type = 0;
    if ($is_login_page) {
        $qrcode_type = 1;
    } else if ($is_my_page) {
        $qrcode_type = 2;
    }

    //如果不是微信，且为登录页或个人中心页
	if (empty($is_weixin) && ($is_xcx_login_my_page === true)) { 
        $wxlogin = kv_get('skiy_xcx_login');
?>
<div class="qrcode-container" style="display: none;">
    <div class="qrcode-title"></div>
    <div id="qrcode" class="qrcode"></div>
</div>
<div class="shade" style="display: none;"></div>
<link rel="stylesheet" href="/plugin/skiy_xcx_login/static/css/common.css">
<script type="text/javascript" src="/plugin/skiy_xcx_login/static/js/jquery.qrcode.min.js"></script>
<?php if ($is_my_page) {?>
<link rel="stylesheet" href="/plugin/skiy_xcx_login/static/css/sweetalert2.min.css">
<script type="text/javascript" src="/plugin/skiy_xcx_login/static/js/sweetalert2.min.js"></script>
<?php } ?>
<script>
    $(function (){
        let qrcode_obj = $('#qrcode');
        let site_url = '<?php echo http_url_path(); ?>';
        let getScanStatus;
        let qrcode_type = '<?php echo $qrcode_type; ?>';
        let [qrcode_create_uri,qrcode_scan_uri, qrcode_scan_check_uri] = ['', '', ''];
        let qrcode_number = '';

        //登录
        if (qrcode_type == 1) {
            $('.qrcode-title').html('微信小程序扫码登录');
            qrcode_create_uri = '/?xcx_login-scan-create_qrcode';
            qrcode_scan_uri = '/?xcx_login-scan-scan_qrcode';
            qrcode_scan_check_uri = '/?xcx_login-scan-check_qrcode';

        //绑定    
        } else if (qrcode_type == 2) {
            $('.qrcode-title').html('微信小程序扫码绑定');
            qrcode_create_uri = '/?xcx_login-bind-create_qrcode';
            qrcode_scan_uri = '/?xcx_login-bind-scan_qrcode';
            qrcode_scan_check_uri = '/?xcx_login-bind-check_qrcode';
        }

        //微信登录
        $("#login-xcx").on("click", function(){
            makeQrcode();
        });

        //微信绑定
        $('#bind-xcx').on("click", function(){
            makeQrcode();
        });

        //刷新二维码
        $('.qrcode').on('click', '.obsolete', function(){
            qrcode_number = $('.obsolete').data('code');
            makeQrcode();
        });

        //点击遮罩层隐藏微信登录/绑定框,并停止计时器
        $('.shade').on('click', function(){
            $('.qrcode-container').hide();
            $('.shade').hide();
            clearInterval(getScanStatus);
        });

        //解除微信绑定
        $('#unbind-xcx').on("click", function(){
            unbindWechatXcx();
        });

        //定时器检测是否扫描
        let scanQrcodeCheck = () => {
            //定时器
            getScanStatus = setInterval(() => {
                $.xget(qrcode_scan_check_uri + '.htm', function(code, message) {
                    //登录成功转跳
                    if (code == 0) {
                        clearInterval(getScanStatus);

                        if (qrcode_type == 1) {
                            window.location.href = site_url;
                        } else if (qrcode_type == 2) {
                            window.location.href = site_url + 'my.htm';
                        }

                    //二维码无效，停止计时(可增加刷新状态)    
                    } else if (code == -1) {
                        clearInterval(getScanStatus);

                        let qrcode_html = `<div class="obsolete" data-code="${message.qrcode}">二维码已失效，点此刷新</a>`;
                        qrcode_obj.html(qrcode_html);

                        //刷新二维码
                        // makeQrcode();

                    //自定义错误
                    } else if (code == 2) {
                        clearInterval(getScanStatus);

                        let qrcode_html = `<div class="obsolete" data-code="">${message.errmsg}，点此刷新</a>`;
                        qrcode_obj.html(qrcode_html);
                    //未扫码    
                    } else if (code == 1) {
                    } else {
                        clearInterval(getScanStatus);

                        let qrcode_html = `<div class="obsolete" data-code="">未知错误，点此刷新</a>`;
                        qrcode_obj.html(qrcode_html);
                    }
                });
            }, 1500); //每1.5s
        };

        //创建登录/绑定二维码
        //参数带旧二维码,刷新时会删除旧二维码在cache的数据
        let makeQrcode = () => {
            let qrcode_create_url = (qrcode_number == '') ? qrcode_create_uri : qrcode_create_uri + '-' + qrcode_number;
            let type = (qrcode_type == 1) ? 'login' : 'bind';

            $.xget(qrcode_create_url + '.htm', function(code, message) {
                if (code == 0) {
                    // qrcode_url = site_url + qrcode_scan_uri + '-' + message.qrcode + '.htm';

                    let dataObj = {
                        type: type,
                        qrcode: message.qrcode,
                    };
                    let data = Base64.encode(JSON.stringify(dataObj));

                    qrcode_obj.html('').qrcode({
                        width: 180,
                        height: 180,
                        text: data
                    });

                    $('.qrcode-container').show();
                    $('.shade').show();

                    //定时检测二维码登录状态
                    scanQrcodeCheck();
                }
            });
        };

        //解除微信绑定
        let unbindWechatXcx = () => {
            let unbind_url = '/?xcx_login-unbind';
            $.xget(unbind_url + '.htm', function(code, message) {
                console.log(code, message);
                //登录成功刷新当前页面
                if (code == 0) {
                    swal({
                        type: 'success',
                        text: '解绑成功',
                        timer: 3000,
                    }).then((result) => {
                        location.reload();
                    });
                } else if (code == 1) {
                    swal({
                        type: 'error',
                        text: message,
                    });
                } else {
                    swal({
                        type: 'error',
                        text: '未知错误',
                    });
                }
            });
        }

        let Base64 = {
            encode(str) {
                // first we use encodeURIComponent to get percent-encoded UTF-8,
                // then we convert the percent encodings into raw bytes which
                // can be fed into btoa.
                return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
                    function toSolidBytes(match, p1) {
                        return String.fromCharCode('0x' + p1);
                    }));
            },
            decode(str) {
                // Going backwards: from bytestream, to percent-encoding, to original string.
                return decodeURIComponent(atob(str).split('').map(function (c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
            }
        };
	});
</script>
<?php } ?>